/*
 * @lc app=leetcode.cn id=15 lang=cpp
 *
 * [15] 三数之和
 */

// @lc code=start
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        std::sort(nums.begin(), nums.end());


        vector<vector<int>> results;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] > 0)
                break;

            //元组之间去重
            if (i > 0 && nums[i] == nums[i - 1])
                continue;

            int l = i + 1, r = nums.size() - 1;
            while (l < r) {
                int t = nums[i] + nums[l] + nums[r];
                if (t == 0) {
                    results.push_back(vector<int>{ nums[i], nums[l], nums[r] });

                    //元组内元素去重
                    while (r > l && nums[r] == nums[r - 1]) r--;
                    while (r > l && nums[l] == nums[l + 1]) l++;

                    l++;
                    r--;
                }

                else if (t > 0)
                    r--;
                
                else
                    l++;
            }
        }

        return results;
    }
};
// @lc code=end

